package com.example.utils;

import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA 加密解密<br/>
 * 1. 首先服务器生成一个秘钥对(包含publicKey和privateKey), 然后将publicKey交给客户端, 服务器端保存privateKey
 * 2. 客户端, 通过 publicKey 对json进行加密(加密方法 encryptByPublicKey(content, publicKey))得到一个加密的串 encryptString, 将这个 encryptString传递给服务器
 * 3. 服务器拿到这个string之后, 首先进行签名验证:
 *
 * @author chenkui
 */
public class RSAUtils {

    /**
     * 非对称密钥算法
     */
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * 签名算法
     */
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 密钥长度
     */
    private static final int KEY_SIZE = 1024;

    /**
     * 密钥长度 注意明文长度是否超过密文长度减去11字节
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * 分块加密长度
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 公钥
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 私钥
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * 公钥类型
     */
    private static final int PUBLIC_SECRET = 1;

    /**
     * 私钥类型
     */
    private static final int PRIVATE_SECRET = 2;

    /**
     * 生成密钥对(公钥和私钥)
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        // 随机数生成器
        SecureRandom sr = new SecureRandom();
        // 设置秘钥的长度为 KEY_SIZE = 1024
        keyPairGen.initialize(KEY_SIZE, sr);
        // 开始创建
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        // 存储 加密对
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64Utils.decodeFromString(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return Base64Utils.encodeToString(signature.sign());
    }

    /**
     * 校验数字签名
     *
     * @param data      已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign      数字签名
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception {
        byte[] keyBytes = Base64Utils.decodeFromString(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64Utils.decodeFromString(sign));
    }

    /**
     * 私钥解密
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String encryptedData, String privateKey) throws Exception {
        return processBlock(encryptedData, privateKey, PRIVATE_SECRET, Cipher.DECRYPT_MODE);
    }

    /**
     * 公钥解密
     *
     * @param encryptedData 已加密数据
     * @param publicKey     公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String encryptedData, String publicKey) throws Exception {
        return processBlock(encryptedData, publicKey, PUBLIC_SECRET, Cipher.DECRYPT_MODE);
    }

    /**
     * 公钥加密
     *
     * @param data      源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String data, String publicKey) throws Exception {
        return processBlock(data, publicKey, PUBLIC_SECRET, Cipher.ENCRYPT_MODE);
    }

    /**
     * 私钥加密
     *
     * @param data       源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String data, String privateKey) throws Exception {
        return processBlock(data, privateKey, PRIVATE_SECRET, Cipher.ENCRYPT_MODE);
    }

    /**
     * 分段加密
     *
     * @param dataStr
     * @param key
     * @param keyType 1:公钥，2：私钥
     * @param mode
     * @return
     * @throws Exception
     */
    private static String processBlock(String dataStr, String key, int keyType, int mode) throws Exception {
        byte[] keyBytes = Base64Utils.decodeFromString(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Key keySecret = null;
        if (keyType == PUBLIC_SECRET) {
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            keySecret = keyFactory.generatePublic(x509KeySpec);
        }
        if (keyType == PRIVATE_SECRET) {
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            keySecret = keyFactory.generatePrivate(pkcs8KeySpec);
        }
        int maxSize = (mode == Cipher.ENCRYPT_MODE ? MAX_ENCRYPT_BLOCK : MAX_DECRYPT_BLOCK);
        cipher.init(mode, keySecret);
        byte[] data = (mode == Cipher.ENCRYPT_MODE ? dataStr.getBytes() : Base64Utils.decodeFromString(dataStr));
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > maxSize) {
                cache = cipher.doFinal(data, offSet, maxSize);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * maxSize;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        if (mode == Cipher.ENCRYPT_MODE) {
            return Base64Utils.encodeToString(encryptedData);
        }
        if (mode == Cipher.DECRYPT_MODE) {
            return new String(encryptedData);
        }
        return null;
    }

    /**
     * 获取私钥 进行base64 转码
     *
     * @param keyMap 密钥对
     * @return
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return Base64Utils.encodeToString(key.getEncoded());
    }

    /**
     * 获取公钥 进行base64 转码
     *
     * @param keyMap 密钥对
     * @return
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return Base64Utils.encodeToString(key.getEncoded());
    }

    /**
     * 测试方法
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String content = "MN5mLeCJd/nFCxnULxjxOWtkxwm3la1g8ZBaFQaaxocKKakZ5fnxOdEbNq34Z18KwBPJX9pgD6XG8tC/Ax+3+J9GY9leTwBF3q2dkiQ/iPVnc8sKfcz9rBwv77Qq7Fhiuhl2s3TtYxjSVBJ4+TMXZld/r6OLqiPjsE8ynhnpM/RdFoE5GwiUd54v49sChlqFV5JvafqfFt8YwAwtLuaBhghITOAzQmdq1ijp5C0b8nd08dQrpkBtxblO70Thbkff70AsuognmlfZjNjnLX54mt8iPPmgnrDn3hfyBluCX+5XJppdLR4GselGEYj5L5No7FNq32NagTFY0yDLQibvGHy8rkaXoF1tOaIuDiM1BYTE6vM0Yj6DoQ9jLRozG1gSG/ZQZ25BxtwUAK9aQrthvw6lHC7vesyiaOmE9916gaBTbxFdF4ytly04f9cSTzVwLA5gcigxv5j6G8UqgUfnDPEXZV0zRK0x7+FiH3yInwEJCPO+bo2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thRz3AXg7wDNMpRl2qE/RgQcMnYHpMCAcRe97JWORVdU6W2T8YJuDuGijxY5+vjp/m9O+loMljkbIlPRxrR+3zyXrSfdb79L8kyWR3icxu0Y3lOP4uIKeqjegmutZZtYcL0qFVWDe+j6xGfjpB+VdO6FZnKpDvmATXC9xG2lKHwetvksy5l1/Xl4FMeux+0Ex1nOaxxewx7vHIZRs9utDfDHrJtwJfoxth29cWAhdTJBEbcgs+q1vaVsIPM7kSq6X1rhLMn5x5qKuYRvEqbQa2d0wFwe9lf6vKR/mbMPQ6yC/Q==";
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRLJ62x5RhCXhgT+mxBA1H41vIB534BD/A/j9Wn6Jo/i5nTN/6lmLWkjEhrZ+9KrNtFSyETbD7+7hb8sya26F5OTNjUxeXQnI3RBuw82yKt8g5LEn3XN++3+tJIb9dSeJ+GHyBQ58zUYS+sZAwQod+eisTOuOWS+r6CYpmE3Sd8QIDAQAB";
        System.out.println("明文：" + content);
        System.out.println("4.公钥解密：" + decryptByPublicKey(content, publicKey));

    }
}